﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using YunCMS.Common;
using YunCMS.BLL;
using YunCMS.Model;

namespace YunCMS.Web.Admin.Catogory
{
    public partial class EditCategory : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string action = Request.QueryString["action"];
                int id;
                string module = Request.QueryString["module"];
                if (string.IsNullOrEmpty(module))
                {
                    JScript.Alert("模块选择不正确", this);
                    return;
                }
                else
                {
                    ViewState["module"] = module;
                }

                TreeBind(module);
                //BindModuleType();
                if (!string.IsNullOrEmpty(action) && action == "edit")//add first level, child level
                {
                    string _id = Request.QueryString["id"];
                    if (!int.TryParse(_id, out id))
                        id = 0;

                    ViewState["ID"] = id;
                    DataBind(id);

                    saveBt.Text = "更新";
                }
                else
                {
                    string parent = Request.QueryString["parent"];
                    if (!string.IsNullOrEmpty(parent))
                    {
                        SelectDllItem(parent);
                    }
                    saveBt.Text = "新增";                    
                }   
            }
        }

        //private void BindModuleType()
        //{
        //    this.ModuleTypeDDL.DataSource = Const.Modules;
        //    this.ModuleTypeDDL.DataTextField = "value";
        //    this.ModuleTypeDDL.DataValueField = "key";
        //    this.ModuleTypeDDL.DataBind();
        //}

        private void DataBind(int id)
        {
            YCCategoryBLL bll = new YCCategoryBLL();

            if (bll.IsExist(id))
            {
                YCCategory model = bll.GetYCCategory(id);
                FillControls(model);
            }
            else
            {
                JScript.Alert("不存在该条记录", this);
            }
        }

        private void TreeBind(string moduleType)
        {
            YCCategoryBLL bll = new YCCategoryBLL();
            IList<YCCategory> list = bll.GetList(moduleType);

            this.parentIdDDL.Items.Clear();
            this.parentIdDDL.Items.Add(new ListItem("无父级分类", "0"));
            foreach (YCCategory item in list)
            {
                string id = item.ID.ToString();
                int classLayer = 0;
                if (item.NodeLevel.HasValue)
                {
                    classLayer = item.NodeLevel.Value;
                }
                string title = item.Title.ToString().Trim();

                ListItem li = new ListItem();
                li.Value = id + "&" + classLayer.ToString() + "&" + item.NodePath;
                if (classLayer != 1)
                {
                    title = "├ " + title;
                    title = StringUtil.NString(classLayer - 1, "　") + title;
                }
                li.Text = title;
                this.parentIdDDL.Items.Add(li);
            }
        }

        private void FillControls(YCCategory model)
        {
            SelectDllItem(model.ParentID.ToString());
            TitleTB.Text = model.Title.ToString();
            //ModuleTypeDDL.SelectedValue = model.ModuleType.ToString();
            if (model.Active.HasValue)
                ActiveCB.Checked = model.Active.Value;

            TargetTB.Text = model.Target.ToString();
            DescriptionTB.Text = model.Description.ToString();
            ContentTB.Text = model.Content.ToString();

            if (model.OrderNumber.HasValue)
                OrderNumberTB.Text = model.OrderNumber.Value.ToString();

            if (model.DisplayType.HasValue)
                DisplayTypeTB.Text = model.DisplayType.Value.ToString();

            ImageUrlTB.Text = model.ImageUrl.ToString();
            KeywordsTB.Text = model.Keywords.ToString();
            //FolderTB.Text = model.Folder.ToString();
            FilePathTB.Text = model.FilePath.ToString();
            OuterLinkTB.Text = model.OuterLink.ToString();
        }

        private void SelectDllItem(string id)
        {
            foreach (ListItem item in parentIdDDL.Items)
            {
                string[] values = item.Value.Split('&');
                if (values[0] == id)
                {
                    item.Selected = true;
                    break;
                }
            }
        }

        private void ParseDllValue(YCCategory model)
        {
            List<string> values = parentIdDDL.SelectedValue.Split('&').ToList();
            int pid, nodeLevel;
            if (!int.TryParse(values[0], out pid))
            {
                pid = 0;
            }
            model.ParentID = pid;
            if (values.Count == 1)
            {
                model.NodePath = "|";
                model.NodeLevel = 1;
            }
            else if(values.Count == 3)
            {
                if (!int.TryParse(values[1], out nodeLevel))
                {
                    nodeLevel = 0;
                }
                model.NodeLevel = ++nodeLevel;

                model.NodePath = values[2] + "|" + pid;
            }

        }

        private void FillModel(YCCategory model)
        {

            string id = parentIdDDL.SelectedValue,
                module = ViewState["module"].ToString();
            if (!string.IsNullOrEmpty(module))
            {
                model.ModuleType = module;
            }
            int displayType, orderNum;

            model.Title = TitleTB.Text.Trim();
            
            model.Active = ActiveCB.Checked;
            model.Target = TargetTB.Text.Trim();
            model.Description = DescriptionTB.Text.Trim();
            model.Content = ContentTB.Text.Trim();

            if (!int.TryParse(OrderNumberTB.Text.Trim(), out displayType))
            {
                displayType = 0;
            }
            model.OrderNumber = displayType;
            if (!int.TryParse(DisplayTypeTB.Text.Trim(), out orderNum))
            {
                orderNum = 0;
            }
            model.DisplayType = orderNum;

            model.ImageUrl = ImageUrlTB.Text.Trim();
            model.Keywords = KeywordsTB.Text.Trim();
            //model.Folder = FolderTB.Text.Trim();
            model.FilePath = FilePathTB.Text.Trim();
            model.OuterLink = OuterLinkTB.Text.Trim();

            ParseDllValue(model);
        }

        protected void saveBt_Click(object sender, EventArgs e)
        {
            YCCategoryBLL bll = new YCCategoryBLL();
            YCCategory model;
            int i = 0, id;

            string action = Request.QueryString["action"];
            if (!string.IsNullOrEmpty(action) && action == "edit")
            {
                if (ViewState["ID"] != null)
                {
                    id = System.Convert.ToInt32(ViewState["ID"]);
                    model = bll.GetYCCategory(id);
                    FillModel(model);
                    i = bll.Update(model);
                };
            }
            else
            {
                model = new YCCategory();
                FillModel(model);
                i = bll.Add(model);
            }
            string  module = ViewState["module"].ToString();
            if (i > 0 && !string.IsNullOrEmpty(module))
            {
                Response.Redirect("CategoryList.aspx?module=" + module);
            }
        }
    }
}